import { defineConfig } from 'rollup';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace';
import postcss from 'rollup-plugin-postcss';
import copy from 'rollup-plugin-copy';
import terser from '@rollup/plugin-terser';
import typescript from 'rollup-plugin-typescript';
import alias from '@rollup/plugin-alias';

const isProduction = process.env.NODE_ENV === 'production';

export default defineConfig({
  input: 'src/index.tsx',
  output: {
    file: 'popup.js',
    format: 'iife',
    name: 'PGZDM',
    sourcemap: !isProduction
  },
  plugins: [
    alias({
      entries: [
        { find: '@monaco-editor/react', replacement: './src/vendor/monaco-editor-react.tsx' }
      ]
    }),
    typescript({
      tsconfig: './tsconfig.json'
    }),
    resolve({
      browser: true,
      preferBuiltins: false
    }),
    commonjs(),
    replace({
      'process.env.NODE_ENV': JSON.stringify(isProduction ? 'production' : 'development'),
      preventAssignment: true
    }),
    postcss({
      extract: 'popup.css',
      minimize: isProduction,
      plugins: [
        (await import('tailwindcss')).default,
        (await import('autoprefixer')).default
      ]
    }),
    copy({
      targets: [
        { src: 'src/manifest.json', dest: '.' },
        { src: 'src/popup.html', dest: '.', rename: 'popup.html' },
        { src: 'src/icons/**/*', dest: 'icons' },
        { src: 'src/agents-config.json', dest: '.' },
        { src: 'src/background.js', dest: '.' },
        { src: 'src/base-agent.js', dest: '.' },
        { src: 'src/lib/chrome-web-content.js', dest: 'lib' },
        { src: 'src/lib/interactive-elements.js', dest: 'lib' },
        { src: 'src/tools/**/*', dest: 'tools' },
        { src: 'src/openrouter-client.js', dest: '.' },
        { src: 'src/markdown-renderer.js', dest: '.' },
        { src: 'src/mcp-client.js', dest: '.' },
        { src: 'src/prompt/**/*', dest: 'prompt' },
        { src: 'node_modules/monaco-editor/min/vs/**/*', dest: 'vs' }
      ]
    }),
    isProduction && terser()
  ].filter(Boolean),
  external: ['chrome']
});
